<template>
    <div class="card">
        <chat-list :id.sync="wechat_id"></chat-list>
        <div v-if="wechat_id">
            <div class="card-body">
                <div class="form-group">
                    <label>素材标题</label>
                    <input type="text"
                           class="form-control" v-model="content.title">

                </div>
                <image-single :image.sync="content.picurl"></image-single>
            </div>
            <div class="card-footer text-muted">
                <div class="btn-group">
                    <button type="button" class="btn btn-primary" @click.prevent="submit">
                        保存提交
                    </button>
                    <a href="/wechat/material?type=image" class="btn btn-outline-info">
                        返回图片素材列表
                    </a>
                </div>
            </div>
        </div>

    </div>
</template>
<script>
    import ImageSingle from '../ImageSingle';
    import ChatList from "./ChatList";

    export default {
        props: {
            material_id: {type: Number, default: 0},
        },
        components: {
            ChatList,
            ImageSingle,
        },
        data() {
            return {
                content: {
                    title: '',
                    picurl: '',
                },
                wechat_id: 0,
            }
        },
        mounted() {
            if (this.material_id) {
                this.getMaterial(this.material_id);
            }
        },
        methods: {
            async getMaterial(id) {
                let api = `wechat/material/${id}`;
                let response = await this.axios.get(api);
                this.content = response.content;
                this.wechat_id = response.wechat_id;
            },
            async submit() {
                let error = [];
                let response; //response如果放在if{}内部，会包裹在块级作用域下，块外面无法调用
                if (this.content.picurl.trim() == '') {
                    error.push('请选择图片');
                }
                if (this.content.title.trim() == '') {
                    error.push('请填写图片标题');
                }
                if (error.length > 0) {
                    error.map(item => {
                        return this.$message.error(item);
                    })
                    return
                }
                if (this.material_id) {
                    response = await this.axios.put(`wechat/material/${this.material_id}`);
                } else {

                    response = await this.axios.post(`wechat/material`, this.$data);
                }

                if (response['route']) {
                    window.location.href = response['route'];
                }

            },

        }
    }
</script>
<style lang="scss">

</style>
